package com.example.demo.service.impl;

import com.example.demo.bean.Profession;
import com.example.demo.common.ServerResponse;
import com.example.demo.dao.ProfessionRepository;
import com.example.demo.service.ProfessionService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

/**
 * Created by IntelliJ IDEA.
 *
 * @author ouyangzhixiang
 * @date 2018/6/23
 */
@Service
@AllArgsConstructor
public class ProfessionServiceImpl implements ProfessionService {
    private final ProfessionRepository professionRepository;
    @Override
    public ServerResponse<List<Profession>> list(Integer parentId) {
        List<Profession> professionList =professionRepository.findByParentIdOrderById(parentId);
        if (professionList.isEmpty()){
            return ServerResponse.createByErrorMessage("没有相关记录");
        }
        return ServerResponse.createBySuccessMessage("成功",professionList);
    }

    @Override
    public ServerResponse findOne(Integer id) {
        Optional<Profession> profession =professionRepository.findById(id);
        if (profession.isPresent()){
            return ServerResponse.createBySuccessMessage("安全域结构是",profession);
        }
        return ServerResponse.createByErrorMessage("没有查询到相关安全域结构");
    }

    @Override
    public ServerResponse<Profession> addProfession(Profession profession) {

        Profession professionAdd = professionRepository.save(profession);
        return ServerResponse.createBySuccessMessage("添加成功", professionAdd);
    }

    @Override
    public void deleteProfession(Integer id) {
        professionRepository.deleteById(id);
    }

    @Override
    public ServerResponse<Profession> professionUpdate(Profession profession) {
        Profession professionUpdate = new Profession();
        professionUpdate.setParentId(profession.getParentId());
        professionUpdate.setName(profession.getName());
        professionUpdate.setId(profession.getId());
        if(professionUpdate==null){
            ServerResponse.createByErrorMessage("填入需要更新字段");
        }
        profession = professionRepository.save(professionUpdate);
        return ServerResponse.createBySuccessMessage("更新成功",profession);
    }
}
